import axios from "axios";
// 导入公共接口地址
import { CONFIG } from "@config";

import { useGlobalStore } from "@stores";

// 创建实例化
const instance = axios.create({
  // baseURL: CONFIG.BASE_URL,
  baseURL: "/api",
  timeout: 6000,
});

// 请求拦截
instance.interceptors.request.use(
  (config) => {
    const token = useGlobalStore().userStore.token;
    if (token) {
      config.headers["Authorization"] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 封装get post

const http = {
  get<T>(url: string, params?: {}, config?: {}): Promise<T> {
    return new Promise((resolve, reject) => {
      instance
        .get<T>(url, { params, ...config })
        .then((res) => {
          resolve(res.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  post<T>(url: string, data?: {}, config?: {}): Promise<T> {
    return new Promise((resolve, reject) => {
      instance
        .post<T>(url, data, config)
        .then((res) => {
          resolve(res.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};

export default http;
